<template>
  <div>
    <!-- <div class="topimg" :class="{ hidden: isHidden }">
  <img src="../assets/images/首页图片.png" alt="Top Image">
</div> -->
    <header class="header">
      <!-- Left section with logo -->
      <div class="logo-section">
        <h1>种花吧</h1>
      </div>

      <!-- Right section with search and user actions -->
      <div class="right-section">

        <el-dropdown>
      <span class="el-dropdown-link">
        快捷功能<i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item  @click.native="toshoppingcart(userData.userId)" icon="el-icon-shopping-cart-2" >我的购物车</el-dropdown-item>
        <el-dropdown-item icon="el-icon-shopping-bag-1" @click.native="tofavorite">商品收藏</el-dropdown-item>
        <el-dropdown-item icon="el-icon-location" @click.native="toAddressManage">地址管理</el-dropdown-item>
        <el-dropdown-item icon="el-icon-switch-button" @click.native="logout">退出登录</el-dropdown-item>
        <el-dropdown-item icon="el-icon-user" @click.native="drawer = true">个人信息</el-dropdown-item>
        <el-dropdown-item icon="el-icon-circle-plus-outline" @click.native="addFriend">添加好友</el-dropdown-item>
        <el-dropdown-item icon="el-icon-circle-plus-outline" @click.native="toAdmin">管理登录</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

        <div class="search-container">
          <input type="text" placeholder="Search..." @keyup.enter="performSearch" />
          <el-button icon="el-icon-search" @click="performSearch" circle></el-button>
        </div>
        <!-- <div class="user-actions">
          <template v-if="!isAuthenticated">
            <el-button @click="goToLogin" round>登录/注册</el-button>
          </template>
          <template v-else>
            <el-avatar :size="36" :src="userData.avatarUrl"></el-avatar>
            <p>{{ userData.username }}</p>
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
                <el-dropdown-item @click.native="drawer = true">个人信息</el-dropdown-item>
                <el-dropdown-item @click.native="addFriend">添加好友</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </div> -->
      </div>
    </header>

    <!-- Drawer for personal information -->
    <el-drawer
      :visible.sync="drawer"
      :with-header="false"
      size="30%"
    >
      <div style="width: 100%; box-shadow: 5px 5px 5px #888888; padding: 20px;">
        <el-form label-width="80px" style="max-width: 400px;">
          <el-form-item>
            <img :src="userData.avatarUrl" class="avatar" alt="User Avatar">
          </el-form-item>
          <el-form-item label="ID">
            <el-input v-model="userData.userId" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="userData.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userData.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input type="textarea" v-model="userData.bio" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div style="text-align: right;">
          <el-button @click="drawer = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isAuthenticated: false, // 初始状态应为未认证
      drawer: false,
      userData: {},
      lastScrollPosition: 0,
      isHidden: true // 新增属性，用于控制 UserHeader 的显示与隐藏
    };
  },
  created() {
    this.loadUserInfo();
  },
  mounted() {
    this.lastScrollPosition = window.pageYOffset || document.documentElement.scrollTop;
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    console.log("进入。。。");
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      
    const currentScrollPosition = window.pageYOffset || document.documentElement.scrollTop;

    // 检查滚动方向
    if (this.lastScrollPosition < currentScrollPosition) {
      console.log("检查滚动方向");
      
      // 向下滚动
      this.isHidden = true;
    } else {
      // 向上滚动
      this.isHidden = false;
    }
    console.log('isHidden:', this.isHidden);

    // 更新上次滚动位置为当前滚动位置
    this.lastScrollPosition = currentScrollPosition;
  },
    loadUserInfo() {
      // 请求分页查询数据
      this.request.get("/users/info").then(res => {
        if (res.code === 1) {
          this.userData = res.data;
          this.isAuthenticated = true;
        } else {
          this.isAuthenticated = false;
        }
      }).catch(err => {
        console.error('Failed to load user info', err);
      });
    },
    save() {
      this.request.post("/user/update", this.userData).then(res => {
        if (res.code === 1) {
          this.$message.success("保存成功");
        } else {
          this.$message.error("保存失败");
        }
      }).catch(err => {
        console.error('Failed to update user info', err);
        this.$message.error("保存失败");
      });
    },
    goToLogin() {
      this.$router.push({ path: '/login' });
    },
    performSearch() {
      console.log('Performing search...');
    },
    logout() {
      // 清除用户认证信息
      localStorage.removeItem('token'); // 清除存储的token
      sessionStorage.removeItem('token'); // 清除会话token
      this.isAuthenticated = false;
      this.userData = {}; // 清空用户数据
      
      // 发送请求到后端注销
      this.request.post("/users/logout").then(res => {
        if (res.code === 1) {
          this.$message({
            type: 'success',
            message: '退出登录成功'
          });
          // 重新加载页面以刷新状态
          window.location.reload();
        }
      }).catch(err => {
        console.error('Logout failed:', err);
        this.$message.error('退出登录失败，请重试');
      });
    },
    toshoppingcart(id){
      //进入购物车
      this.$router.push(`/mycart/${id}`);

    },
    tofavorite(){
      this.$router.push("favorites");
    },
    addFriend() {
      this.$prompt('请输入想要搜索的用户账号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d{1,9}$/,
        inputErrorMessage: '账号格式不正确'
      }).then(({ value }) => {
        this.$router.push(`/otherprofile/${value}`);
        this.$message({
          type: 'success',
          message: '正在跳转...'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    toAddressManage() {
      this.$router.push('/address');
    },
    toAdmin() {
      // 跳转到管理员登录页面
      this.$router.push('/admin/login');
      this.$message({
        type: 'info',
        message: '正在前往管理员登录页面'
      });
    }
  }
};
</script>

<style scoped>
.topimg.hidden {
  opacity: 0;
  transform: translateY(-100%);
  transition: all 0.3s ease-in-out;
}
.topimg img{
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 保持图片比例并裁剪以填满容器 */
  position: relative;
  overflow: hidden;
  /* 确保超出部分被隐藏 */
}
.header {
  background-color: #286090;
  color: white;
  padding: 8px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-section h1 {
  font-size: 20px;
  margin: 0;
}

.right-section {
  display: flex;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-container input {
  height: 30px;
  padding: 0 10px;
  border: none;
  border-radius: 10px;
  width: 150px;
}

.search-container button {
  margin-left: 3px;
  margin-right: 3px;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-actions p {
  margin: 0;
  padding: 0;
}

.el-dropdown-link {
  cursor: pointer;
  color: white;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.avatar-uploader  {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader  {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

/* 修改与抽屉相关的样式 */
.avatar {
  width: 180px;
  height: 180px;
  display: block;
  margin: 0 auto;
}

.el-drawer__body {
  padding: 16px;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-button{
  margin-right: 5px;
}

.el-dropdown-link {
    cursor: pointer;
    color:white;
    margin-right: 5px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .demonstration {
    display: block;
    color: #8492a6;
    font-size: 14px;
    margin-bottom: 20px;
  }

</style>